package com.lvyq.wx.util;

import com.alibaba.fastjson.JSONObject;
import com.lvyq.cache.CacheManager;
import com.lvyq.constant.WeChatCgiBinConstant;
import com.lvyq.util.HttpRequestUtil;

/**
 * @author lvyq
 * @version 1.0
 * @description: 基础api
 * @date 2021/2/20 15:19
 */
public class CgiBinUtil {

    /**
     * @description: 获取token，已做缓存
     * @author: lvyq
     * @date: 2021/2/20 15:22
     * @version 1.0
     */
    public static String getToken(String appId, String appSecret) {
        String requestUrl = WeChatCgiBinConstant.CGI_BIN_TOKEN;
        requestUrl = requestUrl.replace("APPID", appId).replace("APPSECRET", appSecret);
        Object access_token = CacheManager.get("access_token");
        if (access_token == null || "".equals(access_token)) {
            JSONObject object = HttpRequestUtil.httpsRequest(requestUrl, "GET", null);
            if (object != null) {
                try {
                    access_token = object.getString("access_token");
                    System.out.print("JSAPI获取access_token====" + access_token);
                    CacheManager.set("access_token", access_token, 3600 * 1000);
                } catch (Exception e) {
                    System.out.print("获取access_token失败" + object.toString());
                }
            }
        }
        return access_token.toString();
    }

    /**
     * @description: 获取jsapi_ticket
     * @author: lvyq
     * @date: 2021/2/20 15:22
     * @version 1.0
     */
    public static String getTicket(String accessToken) {
        //获取jsapi_ticket（有效期7200秒）
        String requestUrl = WeChatCgiBinConstant.CGI_BIN_GET_TICKET;
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
        Object jsapi_ticket = CacheManager.get("jsapi_ticket");
        if (jsapi_ticket == null || "".equals(jsapi_ticket)) {
            JSONObject object = HttpRequestUtil.httpsRequest(requestUrl, "GET", null);
            if (object != null) {
                try {
                    jsapi_ticket = object.getString("ticket");
                    System.out.print("JSAPI获取jsapi_ticket====" + jsapi_ticket);
                    CacheManager.set("jsapi_ticket", jsapi_ticket, 3600 * 1000);
                } catch (Exception e) {
                    System.out.print("获取ticket失败" + object.toString());
                }
            }
        }
        return jsapi_ticket.toString();
    }
}
